import {
  Body,
  Controller,
  Get,
  Post,
  Query,
  Res,
  HttpCode,
} from "@nestjs/common";
import { Response } from "express";
import { UserService } from "../services/user.service";

// 统一返回结构 { code, msg, data }
const ok = (data: any = null) => ({ code: 0, msg: "success", data });
const fail = (msg: string, code = -1) => ({ code, msg });

@Controller("/user-service/user")
export class UserController {
  constructor(private readonly userService: UserService) {}
  @Post("/login")
  @HttpCode(200)
  async login(@Body() body: any) {
    // 入参: { mobile, pwd, captcha }
    // 返回: { userId, accessToken }
    if (!body?.mobile || !body?.pwd) {
      return fail("参数错误");
    }
    const res = await this.userService.login(body.mobile, body.pwd);
    if (!res) return fail("账号或密码错误");
    return ok({ userId: res.user.id, accessToken: res.token });
  }

  @Post(["/register"]) // 可能使用 post/json
  @HttpCode(200)
  async register(@Body() body: any) {
    // 入参: { mobile, pwd, captcha, channel?, code? }
    if (!body?.mobile || !body?.pwd || !body?.captcha) {
      return fail("参数错误");
    }
    try {
      await this.userService.register(
        body.mobile,
        body.pwd,
        body.channel || null,
        body.code || null
      );
      return ok(true);
    } catch (e: any) {
      console.error("注册用户时发生错误:", e);
      if (e?.message === "MOBILE_EXISTS") return fail("该手机号已注册", 4001);
      return fail(`服务器错误: ${e?.message || e}`);
    }
  }

  @Post(["/resetPwd"]) // form 提交
  @HttpCode(200)
  async resetPwd(@Body() body: any) {
    // 入参: { mobile, pwd, captcha }
    if (!body?.mobile || !body?.pwd || !body?.captcha) {
      return fail("参数错误");
    }
    const okUpdated = await this.userService.resetPassword(
      body.mobile,
      body.pwd
    );
    if (!okUpdated) return fail("用户不存在");
    return ok(true);
  }

  @Post(["/captcha", "/captchaReg"]) // form 提交
  @HttpCode(200)
  captcha(@Body() body: any) {
    // 入参: { mobile, captcha }
    if (!body?.mobile || !body?.captcha) {
      return fail("参数错误");
    }
    // 返回短信验证码
    return ok("123456");
  }

  @Get("/captchaImg")
  captchaImg(@Query("moblie") mobile: string, @Res() res: Response) {
    // 返回一张简单的 1x1 PNG 或占位
    const img = Buffer.from(
      "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAF8wJgN1bqGQAAAABJRU5ErkJggg==",
      "base64"
    );
    res.setHeader("Content-Type", "image/png");
    res.send(img);
  }

  @Get("/weixinAuth")
  weixinAuth(@Query("code") code?: string) {
    if (!code) return fail("缺少code");
    // 返回 openid 模拟
    return ok("mock-openid-" + code.substring(0, 6));
  }

  @Post("/invite/create")
  @HttpCode(200)
  inviteCreate() {
    // 返回邀请码
    return ok("INVITE1234");
  }

  @Get("/invite/my")
  myInvite() {
    // 返回 { code, permission }
    return ok({ code: "INVITE1234", permission: 1 });
  }

  @Post("/invite/list")
  @HttpCode(200)
  inviteList(@Body() body: any) {
    const page = Number(body?.page || 1);
    const pageSize = Number(body?.pageSize || 20);
    const total = 3;
    const list = Array.from({ length: Math.min(pageSize, total) }).map(
      (_, i) => ({
        id: 1000 + i,
        mobile: "1380000000" + i,
        gold: 100 * (i + 1),
        award: 1,
        state: 1,
        createTime: "2025-01-01 12:00:00",
      })
    );
    return ok(list);
  }

  @Post("/invite/rechange")
  @HttpCode(200)
  inviteRechange(@Body() body: any) {
    const page = Number(body?.page || 1);
    const pageSize = Number(body?.pageSize || 50);
    const total = 5;
    const data = Array.from({ length: Math.min(pageSize, total) }).map(
      (_, i) => ({
        id: 2000 + i,
        area: i % 2 === 0 ? 1 : 2,
        name: `玩家${i + 1}`,
        sum: (i + 1) * 1000,
      })
    );
    const sum = data.reduce((acc, cur) => acc + cur.sum, 0);
    return { code: 0, msg: "success", data, total, sum };
  }

  @Get("/getWeixinJsApiSign")
  getWeixinJsApiSign(@Query("url") url?: string) {
    if (!url) return fail("缺少url");
    return ok({
      appId: "wx-mock",
      timestamp: Math.floor(Date.now() / 1000),
      nonceStr: "nonce",
      signature: "signature",
      jsApiList: [],
    });
  }
}
